#include <cstdlib>
#include <cctype>
#include <cstring>
#include "Sock.hpp"
#include "Log.hpp"
#include "Error.hpp"
#include "Protocol.hpp"
#include "Util.hpp"

using namespace std;
enum
{
    LEFT,
    OP,
    RIGHT
};

void transformStruct(ns_Protocol::Request *req, const string& req_str)
{
    int status = LEFT;
    int i = 0;
    // 15+69
    string left;
    string right;
    char op;
    while (i < req_str.size())
    {
        switch (status)
        {
        case LEFT:

            if (isdigit(req_str[i]))
                left.push_back(req_str[i++]);
            else
                status = OP;
            break;
        case OP:
            op = req_str[i++];
            status = RIGHT;
            break;

        case RIGHT:
            right.push_back(req_str[i++]);
            break;
        }
    }
    cout << "left: " << left << endl;
    cout << "op " << op << endl;
    cout << "right: " << right << endl;
    req->_x = Util::toInt(left);
    req->_y = Util::toInt(right);
    req->_op = op;
}

int main()
{
    Sock sock;
    string serverip = "127.0.0.1";
    uint16_t serverport = 8888;
    sock.Socket();
    int n = sock.Connect(serverip, serverport);
    // 进行通信
    int _sock = sock.Fd();
    string inbuf;
    while (true)
    {
        //规定好输入格式：1+1
        cout << "Please enter>>";
        string req_str;
        getline(cin, req_str); 
        ns_Protocol::Request req;
        //将输入的算式，转化为结构化数据
        transformStruct(&req, req_str);
        // 序列化
        req_str.clear();
        req.Serialize(&req_str);

        //添加报头
        req_str = ns_Protocol::addHeaders(req_str);
        
        // 发送到网络
        send(_sock, req_str.c_str(), req_str.size(), 0);
        std::cout << "i send success..." << std::endl;

    START:
        char buf[1024];
        ssize_t s = recv(_sock, buf, sizeof(buf) - 1, 0);
        if (s <= 0)
        {
            sock.Close();
            exit(READ_ERR);
        }
        buf[s] = 0;
        inbuf += buf;
        ns_Protocol::Response resp;
        string resp_str;
        //获取完整报文 "5\r\n1 + 1\r\n"
        int n = ns_Protocol::getPackage(inbuf, &resp_str);
        if (n == 0)
            goto START;
        // 去报头
        resp_str = ns_Protocol::removeHeaders(resp_str, n);
        // 返回序列
        resp.Deserialize(resp_str);
    }

    sock.Close();

    return 0;

}